package com.gupao.vip.trevor.queue.zookeeper;

import org.apache.zookeeper.CreateMode;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.ZooDefs;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;

import java.util.List;

/**
 * <h1></h1>
 * <p>
 * <b>描述：</b>
 * <br>
 * <br>
 * </p>
 *
 * @author Trevor
 * @version 1.0     2017年08月10日  15点22分
 */
public class ZKSession
{

    private ZooKeeper zooKeeper;

    ZKSession(ZooKeeper zooKeeper)
    {
        this.zooKeeper = zooKeeper;
    }

    public byte[] getFirst(boolean delete)
    {
        byte[] data;
        String path = "";
        try
        {
            List<String> children = zooKeeper.getChildren("/queue", false);
            children.sort((a_str, b_str) -> {
                Long a = Long.parseLong(a_str);
                Long b = Long.parseLong(b_str);
                if (a > b)
                    return -1;
                if (a < b)
                    return 1;
                return 0;
            });
            for (int i = children.size() - 1; i > -1 ; i--)
            {
                try
                {
                    Stat stat = new Stat();
                    path = children.get(i);
                    data = zooKeeper.getData("/queue/" + path, false, stat);
                    if (delete)
                        zooKeeper.delete("/queue/" + path, stat.getVersion());
                } catch (Exception e) {
                    // 如果一个进程总是抢不过其他进程，会产生大量多余的请求。考虑重新 getChildren
                    System.out.println(path + "获取失败，对象可能已被其他人获取了，尝试重新获取" + e.getMessage());
                    continue;
                }
                return data;
            }

        } catch (InterruptedException | KeeperException e)
        {
            e.printStackTrace();
        }
        System.out.println("无法获取到数据，可能是队列暂时空了");
        return null;
    }

    public boolean create(byte[] data)
    {
        try
        {
            zooKeeper.create("/queue/", data, ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT_SEQUENTIAL);
            return true;
        } catch (KeeperException | InterruptedException e)
        {
            e.printStackTrace();
        }
        return false;
    }

    public int getSize()
    {
        try
        {
            List<String> children = zooKeeper.getChildren("/queue", false);
            if (children != null)
                return children.size();
        } catch (KeeperException | InterruptedException e)
        {
            e.printStackTrace();
        }
        return 0;
    }
}
